package com.atguigu.gmall.mq.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.mq.config.DelayMessageConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: 封捷
 * @create-date: 2022/9/13 10:00
 */
@Slf4j
@RestController
public class DelayMessageController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/mq/send/delay/message")
    public Result<Void> sendDelayMessage() {

        String message = "I am a really foolish man";

        rabbitTemplate.convertAndSend(
                DelayMessageConfig.EXCHANGE_DELAY,
                DelayMessageConfig.ROUTING_KEY_DELAY,
                message,

                // 基于插件的延迟消息，需要传入 MessagePostProcessor 对象
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {

                        // 对 Message 对象做消息延迟的设置，时间单位是毫秒
                        message.getMessageProperties().setDelay(20 * 1000);

                        return message;
                    }
                }
        );

        log.info("[发送端]" + new SimpleDateFormat("hh:mm:ss").format(new Date()));

        return Result.ok();
    }

}
